#include "qstatisticgraph.h"

#include <iostream>

QStatisticGraph::QStatisticGraph ( QColor color, QString labelString ) : QGraphicsItem()
{
	minY = 0;
	maxY = 0;

	currentIndex = 0;

	this -> labelString = labelString;

	setPen ( color );
}

QStatisticGraph::~QStatisticGraph()
{}

void QStatisticGraph::setPen ( const QPen & pen )
{
	this -> pen = pen;
}

void QStatisticGraph::setBrush ( const QBrush & brush )
{
	this -> brush = brush;
}

QRectF QStatisticGraph::boundingRect() const
{
	return rect;
}

void QStatisticGraph::insertPoint ( QPointF point )
{
	currentIndex = ( int ) point.x();

	if ( point.y() < minY ) minY = point.y();
	if ( point.y() > maxY ) maxY = point.y();

	// point already in list
	if ( points.size() - 1 >= point.x() ) points.replace ( ( int ) point.x(), point );
	// index out of range -> add point
	else points.append ( point );
}

void QStatisticGraph::reset()
{
	minY = 0;
	maxY = 0;

	currentIndex = 0;
	labelX = 15;

	points.clear();
}

void QStatisticGraph::advance ( int phase )
{
	if ( phase == 0 )
	{
		setPos ( 0, scene() -> sceneRect().height() );

		if ( ( currentIndex + 185 ) > scene() -> sceneRect().width() ) labelX = currentIndex - 180;
		else labelX = currentIndex + 15;

		newPoints = QPolygonF ( points.mid ( 0, currentIndex ) );
		oldPoints = QPolygonF ( points.mid ( currentIndex, -1 ) );

		rect = QRectF ( 0, minY, currentIndex, maxY );
	}
	else if ( phase == 1 )
	{
		update ( rect );
	}
}

void QStatisticGraph::paint ( QPainter * painter, const QStyleOptionGraphicsItem*, QWidget* )
{
	// don't run paint() if do not have any data - e.g. before the game starts
	if (currentIndex == 0) return;

	painter -> setBrush ( brush );

	painter -> setPen ( QColor ( pen.color().red(),
	                             pen.color().green(),
	                             pen.color().blue() ) );

	painter -> drawText (
	    labelX,
	    ( int ) newPoints.at ( currentIndex - 1 ).y(),
	    ( QString ) labelString.arg ( - ( newPoints.at ( currentIndex - 1 ) ).y(), 0, 'f', 1 ) );

	painter -> drawPolyline ( newPoints );

	painter -> setPen ( QColor ( pen.color().red(),
	                             pen.color().green(),
	                             pen.color().blue(),
	                             128 ) );
	painter -> drawPolyline ( oldPoints );
}
